#include "drv_watchdog.h"

#if (WATCHDOG_ENABLE == 1)

#ifndef HAL_IWDG_MODULE_ENABLED
#define HAL_IWDG_MODULE_ENABLED
#endif

IWDG_HandleTypeDef hiwdg;
static uint32_t watchdog_feed_counter = 0;

HAL_StatusTypeDef drv_watchdog_init(void)
{
    uint32_t prescaler_value;
    uint32_t reload_value;
    
    // 根据预分频器配置获取数值
    switch(WATCHDOG_PRESCALER)
    {
        case IWDG_PRESCALER_4:   prescaler_value = 4;   break;
        case IWDG_PRESCALER_8:   prescaler_value = 8;   break;
        case IWDG_PRESCALER_16:  prescaler_value = 16;  break;
        case IWDG_PRESCALER_32:  prescaler_value = 32;  break;
        case IWDG_PRESCALER_64:  prescaler_value = 64;  break;
        case IWDG_PRESCALER_128: prescaler_value = 128; break;
        case IWDG_PRESCALER_256: prescaler_value = 256; break;
        default: prescaler_value = 32; break;
    }
    
    // 计算重装载值 (LSI = 40000Hz for STM32F103)
    reload_value = (WATCHDOG_TIMEOUT_MS * 40000) / (prescaler_value * 1000);
    
    // 限制重装载值范围 (0-4095)
    if(reload_value > 4095) reload_value = 4095;
    if(reload_value < 1) reload_value = 1;
    
    hiwdg.Instance = IWDG;
    hiwdg.Init.Prescaler = WATCHDOG_PRESCALER;
    hiwdg.Init.Reload = reload_value;
    
    if (HAL_IWDG_Init(&hiwdg) != HAL_OK)
    {
        return HAL_ERROR;
    }
    
    return HAL_OK;
}

void drv_watchdog_refresh(void)
{
    HAL_IWDG_Refresh(&hiwdg);
}

void drv_watchdog_feed_with_counter(void)
{
    watchdog_feed_counter++;
    if(watchdog_feed_counter >= WATCHDOG_FEED_INTERVAL_COUNT)
    {
        watchdog_feed_counter = 0;
        drv_watchdog_refresh();
    }
}

#endif
